package com.jf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jf.controller.R;
import com.jf.dao.AppVersionDao;
import com.jf.dto.AppInfoDto;
import com.jf.entity.AppInfo;
import com.jf.service.AppInfoService;
import com.jf.dao.AppInfoDao;
import com.jf.entity.AppVersion;
import com.jf.sys.SessionManager;
import com.jf.sys.SysConstant;
import com.jf.vo.LoginUser;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class AppInfoServiceImpl implements AppInfoService {
    @Autowired
    AppInfoDao appInfoDao;
    @Autowired
    AppVersionDao appVersionDao;
    @Override
    public PageInfo<AppInfo> getPage(AppInfoDto appInfoDto, Integer pageNum, Integer pageSize, String token) {
        LoginUser loginUser = (LoginUser) SessionManager.get(token);
        PageHelper.startPage(pageNum,pageSize);
        AppInfo appInfo=new AppInfo();
        BeanUtils.copyProperties(appInfoDto,appInfo);
        //不等于管理员的情况下
        if (loginUser.getType()!= SysConstant.UserTypeInt.admin){
            appInfo.setDevid(loginUser.getId());
        }else {
            appInfo.setStatus(1L);
        }
        PageInfo<AppInfo> pageInfo=new PageInfo<>(appInfoDao.queryAllBy(appInfo));
        return pageInfo;
    }

    @Override
    public R updateAddApp(AppInfo appInfo, MultipartFile log, HttpServletRequest request){
        String token = request.getHeader("Token");
        LoginUser loginUser = (LoginUser) SessionManager.get(token);
        if (log!=null){
            if (!log.isEmpty()){
                String logName = log.getOriginalFilename();
                String extension = FilenameUtils.getExtension(logName);

                if (log.getSize()>1024*1024){
                    return R.error("大小大于1mb");
                }else if (extension.equalsIgnoreCase("jpg")||
                        extension.equalsIgnoreCase("png")||
                        extension.equalsIgnoreCase("gif")||
                        extension.equalsIgnoreCase("jpeg")
                ){
                    String realPath = request.getSession().getServletContext().getRealPath("/upload");
                    File filePath=new File(realPath);
                    if (!filePath.exists()){
                        filePath.mkdirs();
                    }
                    String replaceName = UUID.randomUUID().toString().replace("-", "")+"."+extension;
                    appInfo.setLogopicpath("upload/"+replaceName);
                    File fileUrl=new File(realPath+"/"+ replaceName);
                    try {
                        log.transferTo(fileUrl);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }else {
                    return R.error("文件格式不对");
                }
            }
        }
        if (appInfo.getId()!=null){
            appInfo.setModifyby(loginUser.getId());
            appInfo.setUpdatedate(new Date());
            int update = appInfoDao.update(appInfo);
            return R.success("修改成功",update);
        }else {
            appInfo.setDevid(loginUser.getId());
            appInfo.setStatus(1L);
            appInfo.setCreationdate(new Date());
            appInfo.setDownloads(0L);
            appInfo.setCreatedby(loginUser.getId());
            int insert = appInfoDao.insert(appInfo);
            return R.success("添加成功",insert);
        }
    }


    @Override
    public AppInfo selectApknameInt(String apkName) {
        return appInfoDao.selectApknameInt(apkName);
    }

    @Override
    public int deleteApp(int id,HttpServletRequest request) {
        //删除手游apk文件
        AppVersion appVersion=new AppVersion();
        appVersion.setAppid((long) id);
        List<AppVersion> appVersions = appVersionDao.queryAllByLimit(appVersion);
        for (AppVersion version : appVersions) {
            if (version.getDownloadlink()!=null){
                String realPath = request.getSession().getServletContext().getRealPath(version.getDownloadlink());
                if (realPath!=null){
                    File file=new File(realPath);
                    if (file.exists()){
                        file.delete();
                    }
                }

            }
        }
        //删除手游版本

        appVersionDao.deleteById((long) id);
        //删除手游log图
        AppInfo appInfo = appInfoDao.queryById((long) id);
        String realPath = request.getSession().getServletContext().getRealPath(appInfo.getLogopicpath());
        File file=new File(realPath);
        if (file.exists()){
            file.delete();
        }
        return appInfoDao.deleteById((long) id);
    }

    @Override
    public AppInfo selectById(int id) {
        return appInfoDao.queryById((long) id);
    }

    @Override
    public int update(AppInfo appInfo) {
        return appInfoDao.update(appInfo);
    }

}
